package com.example.prototipoasincrono.async;

import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;

import es.eupt.amazingpi.model.usuario.MensajeUsuario;

public class Cliente {
	Client client;
	final Context context;

	public Cliente (Context contexto) {
		this.context = contexto;
//		this.context = context;
		client = new Client();
		client.start();

		// For consistency, the classes to be sent over the network are
		// registered by the same method for both the client and server.
		Network.register(client);

		client.addListener(new Listener() {
			public void connected (Connection connection) {
				Log.d("","Conectado");
				MensajeUsuario msj = new MensajeUsuario();
				msj.setCodigo(MensajeUsuario.CODIGO_CONEXION);
				msj.setUsername("Jara");
				msj.setPassword("");
				client.sendTCP(msj);
			}

			public void received (Connection connection, Object object) {
				Intent intent = new Intent("respuesta");
		    	intent.putExtra("respuesta", "Ha recibido algo");
		    	LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
			}

			public void disconnected (Connection connection) {
			}
		});


		// We'll do the connect on a new thread so the ChatFrame can show a progress bar.
		// Connecting to localhost is usually so fast you won't see the progress bar.
		new Thread("Connect") {
			public void run () {
				try {
					client.connect(5000, "192.168.96.131", Network.port);
					// Server communication after connection can go here, or in Listener#connected().
				} catch (IOException ex) {
					ex.printStackTrace();
					System.exit(1);
				}
			}
		}.start();
	}

}